package com.dev.weixin.manager.controllers;

import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.dev.security.login.beans.LoginUser;
import com.dev.security.login.service.LoginManager;
import com.dev.security.util.DataGrid;
import com.dev.security.util.Response;
import com.dev.weixin.manager.beans.ImageSource;
import com.dev.weixin.manager.service.IImageSourceService;

/**
 * @author 飘渺青衣
 * @see
 */
@Controller
@RequestMapping("/weixin/image/")
public class ImageSourceController {

	@Autowired
	private IImageSourceService imageSourceService;
	
	@Autowired
	private LoginManager loginManager;
	
	@RequestMapping("browse")
	public @ResponseBody DataGrid<ImageSource> browse(
			HttpServletRequest request, HttpServletResponse response,
			String type, int page, int rows) {
		LoginUser user = this.loginManager.getLoginUser(request, response);
		return this.imageSourceService.findPage(type, user.getUserId(), page, rows);
	}
	
	@RequestMapping("upload")
	public @ResponseBody Map<String, String> upload(
			HttpServletRequest request, HttpServletResponse response,
			String type, @RequestParam("file") MultipartFile file) {
		LoginUser user = this.loginManager.getLoginUser(request, response);
		String path = new StringBuilder()
			.append("/resources/uploads/images/")
			.append(user.getUserId()).append("/").toString(); 
		String dir = request.getServletContext().getRealPath(path);
		int count = this.imageSourceService.upload(type, user.getUserId(), dir, path, file);
		Map<String, String> result = new LinkedHashMap<String, String>();
		result.put("status", count > 0 ? "ok" : "faild");
		return result;
	}
	
	@RequestMapping("remove")
	public @ResponseBody Response remove(
			HttpServletRequest request, HttpServletResponse response, String id) {
		LoginUser user = this.loginManager.getLoginUser(request, response);
		this.imageSourceService.remove(id, user.getUserId());
		return new Response(true);
	}
}
